#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import mysql.connector
import os
import g

class DbMod: 

    def __init__(
        self
    ):
        self._tablename="outline_keys"
        self.mydb = None

        self._connect()

    def _connect(self):

        if not None is self.mydb:
            return 

        g.log.info('Connect to: ' + os.environ['MYSQL_LOCAL_HOST']
          + ':' + os.environ['MYSQL_LOCAL_PORT']
          + ' db:' + os.environ['MYSQL_DATABASE']
          + ' user:' + os.environ['MYSQL_USER']
        )

        self.mydb = mysql.connector.connect(
            host=os.environ['MYSQL_LOCAL_HOST']
          , port=os.environ['MYSQL_LOCAL_PORT']
          , user=os.environ['MYSQL_USER']
          , password=os.environ['MYSQL_PASSWORD']
          , database=os.environ['MYSQL_DATABASE']
        )
        g.log.info("Connected" if self.mydb.is_connected() else "NOT connected")

    def Table(self):
        return self._tablename

    def Select_Impl(
        self
      , q
    ):
        mycursor = self.mydb.cursor(dictionary=True)
        mycursor.execute(q)
        result = mycursor.fetchall()
        mycursor.close()
        return result

    def Commit_Impl(self, q):
        mycursor = self.mydb.cursor()
        mycursor.execute(q)
        self.mydb.commit()
        return mycursor.rowcount

    def SelectKeyByTelegramID(telegramID):
        return []

    def SelectAllKeys(self):
        q = 'select id,ClientTGid,ClientTGname,isActive from ' + self._tablename
        return self.Select_Impl(q)

    def SelectOneKey(self, id):
        q = f"select * from {self._tablename} where id={id}"
        return self.Select_Impl(q)

    def ActivateKey(self, id):
        q = f"update {self._tablename} set isActive=1 where id={id}"
        return 0 != self.Commit_Impl(q)

    def DeactivateKey(self, id):
        q = f"update {self._tablename} set isActive=0 where id={id}"
        return 0 != self.Commit_Impl(q)

    def Insert_Impl(
        self
      , dictData #dict
    ):
        mycursor = self.mydb.cursor()
        cols = ','.join([f'`{k}`' for k in dictData.keys()])
        vals = ','.join(['%s'] * len(dictData))
        stmt = f'INSERT INTO `{self._tablename}` ({cols}) VALUES ({vals})'
        mycursor.execute(stmt, tuple(dictData.values()))
        self.mydb.commit()
        return mycursor.rowcount

    def InsertKey(
        self
      , dictData #dict
    ):
        return 0 != self.Insert_Impl(dictData)
